import API from "../../api/api_solid";
import util from '../../common/util';


/**
 \* Created with IntelliJ IDEA.
 \* User: 彭诗杰
 \* Date: 2018/8/7 19:05
 \* Description: 固废类state
 \*/
const state = {
  solidFactors: [],
  solidSystem: {},
  // 最新数据
  solidLatest: {},
  // 实时数据
  solidPresents: [],
  //分页实时数据
  solidPresentsPagingList: [],
  // 历史数据
  solidHistories: [],
  solidPagination: {
    page: 0,
    limit: 10,
    total: 100,
  },
};

const getters = {
  solidFactors: state => {
    return state.solidFactors;
  },
  solidSystem: state => {
    return state.solidSystem;
  },
  solidHistories: state => {
    return state.solidHistories;
  },
  solidPresents: state => {
    return state.solidPresents;
  },
  solidLatest: state => {
    return state.solidLatest;
  },
  solidPresentsPagingList: state => {
    return state.solidPresentsPagingList;
  }
};

const actions = {

  /**
   * 不分页获取单指标历史数据
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getSolidFactorHistoriesNoPagingAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getSolidHistoriesNoPaging(params).then(result => {
        console.log(result);
        resolve(result);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      })
    })
  },

  /**
   * 按指标获取后台当日实时数据并组装成el-table格式
   *
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getSolidPresentPagingAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let solidHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              solidId: params.solidId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getSolidHistoryValues(factorParams);
            //console.log(factorHistories);
            let formatFactorHistories = factorHistories.factorValueVos;
            //console.log(formatFactorHistories);
            total = factorHistories.total;
            //console.log(total);
            formatFactorHistories.forEach(formatFactorHistory => {
              solidHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(solidHistories, 'time');
      console.log('groupedByTime', groupedByTime)
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
        //console.log(allRows)
      });

      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };
      commit('setSolidPresentPagingList', allRows);
      resolve(pagination);
    })
  },

  /**
   * 按指标获取后台历史数据并组装成el-table格式，草特么的难写
   * @param commit
   * @param state
   * @param params
   * @returns {Promise}
   */
  getSolidHistoryListAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let airHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              solidId: params.solidId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getSolidHistoryValues(factorParams);
            //console.log(factorHistories);
            let formatFactorHistories = factorHistories.factorValueVos;
            total = factorHistories.total;
            formatFactorHistories.forEach(formatFactorHistory => {
              airHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(airHistories, 'time');
      //commit('setSewageHistoriesWithRange', groupedByTime);
      //console.log(groupedByTime);
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
      });
      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };

      commit('setSolidHistoryList', allRows);
      resolve(pagination);
    });
  },

  /**
   * 从服务器获取当前服务区固废监测集成商系统
   * @param commit
   * @param state
   * @param area
   * @returns {Promise<any>}
   */
  getSolidSystemsAct({commit, state}, area) {
    return new Promise((resolve, reject) => {
      API.getSolidSystems(area.solidId).then(systems => {
        resolve(systems);
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * 从服务器获取固废系统监测指标
   * @param commit
   * @param state
   * @param params
   */
  getSolidFactorsAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getSolidFactors(params).then(factPageVo => {
        //commit('setSolidFactors')
        resolve(factPageVo);
        //console.log(factPageVo);
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * 从服务器获取监测指标最新值
   * @param commit
   * @param state
   * @param params {solidId, systemCode, factorCode}
   * @returns {Promise}
   */
  getSolidFactorLatestValueAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getSolidLatestValue(params).then(factorValue => {
        resolve(factorValue);
      }, error => {
        reject(error);
      }).catch(err => {
        reject(err);
      })
    })
  },

  setSolidSystemAct({commit, state}, system) {
    commit('setSolidSystem', system);
  },

  setSolidHistoryList({commit, state}, data) {
    commit('setSolidHistoryList', data);
  },

  setSolidPresentPagingList({commit, state}, entity) {
    commit('setSolidPresentPagingList', entity);
  },

};
const mutations = {
  setSolidPresentPagingList(state, entity) {
    state.solidPresentsPagingList = entity;
  },
  setSolidHistoryList(state, entity) {
    state.solidHistories = entity;
  },
  setSolidFactors(state, entity) {
    state.solidFactors = entity;
  },
  setSolidSystem(state, entity) {
    state.solidSystem = entity;
  }
};
export default {
  state,
  getters,
  actions,
  mutations
}
